import 'package:flutter/material.dart';
import '../../theme/theme.dart';

/// 按钮类型，对应Miaoyi框架中的按钮样式
enum MyButtonType {
  /// 默认按钮
  defaultType,
  
  /// 主要按钮
  primary,
  
  /// 成功按钮
  success,
  
  /// 信息按钮
  info,
  
  /// 警告按钮
  warning,
  
  /// 危险按钮
  danger,
  
  /// 白色按钮
  white,
  
  /// 链接按钮
  link
}

/// 按钮尺寸，对应Miaoyi框架中的按钮大小
enum MyButtonSize {
  /// 大号按钮
  large,
  
  /// 默认大小
  normal,
  
  /// 小号按钮
  small,
  
  /// 迷你按钮
  mini
}

/// Miaoyi UI框架按钮组件
/// 
/// 实现了Miaoyi框架中的按钮样式，支持不同类型和大小
class MyButton extends StatefulWidget {
  /// 创建一个Miaoyi风格的按钮
  ///
  /// [text] 按钮显示的文本
  /// [type] 按钮类型，对应Miaoyi框架中的不同颜色样式
  /// [size] 按钮大小
  /// [outline] 是否为线性按钮（仅显示边框）
  /// [block] 是否为块级按钮（宽度填满父容器）
  /// [disabled] 是否禁用
  /// [onPressed] 点击回调
  /// [icon] 可选的图标
  const MyButton({
    super.key,
    required this.text,
    this.type = MyButtonType.defaultType,
    this.size = MyButtonSize.normal,
    this.outline = false,
    this.block = false,
    this.disabled = false,
    this.onPressed,
    this.icon,
  });

  /// 按钮显示的文本
  final String text;
  
  /// 按钮类型
  final MyButtonType type;
  
  /// 按钮大小
  final MyButtonSize size;
  
  /// 是否为线性按钮
  final bool outline;
  
  /// 是否为块级按钮
  final bool block;
  
  /// 是否禁用
  final bool disabled;
  
  /// 点击回调
  final VoidCallback? onPressed;
  
  /// 可选图标
  final IconData? icon;

  @override
  State<MyButton> createState() => _MyButtonState();
}

class _MyButtonState extends State<MyButton> {
  bool _isHovered = false;
  bool _isPressed = false;

  /// 根据按钮类型获取颜色
  Color _getButtonColor(HTheme theme) {
    final colors = theme.colors;
    
    if (widget.disabled) {
      return widget.outline 
          ? Colors.transparent 
          : colors.disabledBackground;
    }
    
    if (widget.outline) {
      return Colors.transparent;
    }
    
    if (_isPressed) {
      // 按下状态颜色
      switch (widget.type) {
        case MyButtonType.primary:
          return colors.primaryDark;
        case MyButtonType.success: 
          return colors.successDark;
        case MyButtonType.info:
          return colors.infoDark;
        case MyButtonType.warning:
          return colors.warningDark;
        case MyButtonType.danger:
          return colors.dangerDark;
        case MyButtonType.white:
          return const Color(0xFFF0F0F0);
        case MyButtonType.link:
          return Colors.transparent;
        case MyButtonType.defaultType:
          return const Color(0xFFD9D9D9);
      }
    } else if (_isHovered) {
      // 悬停状态颜色
      switch (widget.type) {
        case MyButtonType.primary:
          return Color.lerp(colors.primary, colors.primaryDark, 0.5)!;
        case MyButtonType.success:
          return Color.lerp(colors.success, colors.successDark, 0.5)!;
        case MyButtonType.info:
          return Color.lerp(colors.info, colors.infoDark, 0.5)!;
        case MyButtonType.warning:
          return Color.lerp(colors.warning, colors.warningDark, 0.5)!;
        case MyButtonType.danger:
          return Color.lerp(colors.danger, colors.dangerDark, 0.5)!;
        case MyButtonType.white:
          return const Color(0xFFF9F9F9);
        case MyButtonType.link:
          return Colors.transparent;
        case MyButtonType.defaultType:
          return const Color(0xFFE0E0E0);
      }
    }
    
    // 默认状态颜色
    switch (widget.type) {
      case MyButtonType.primary:
        return colors.primary;
      case MyButtonType.success:
        return colors.success;
      case MyButtonType.info:
        return colors.info;
      case MyButtonType.warning:
        return colors.warning;
      case MyButtonType.danger:
        return colors.danger;
      case MyButtonType.white:
        return Colors.white;
      case MyButtonType.link:
        return Colors.transparent;
      case MyButtonType.defaultType:
      return const Color(0xFFE6E6E6); // 默认按钮灰色背景
    }
  }

  /// 根据按钮类型获取文本颜色
  Color _getTextColor(HTheme theme) {
    final colors = theme.colors;
    
    if (widget.disabled) {
      return widget.outline ? colors.textDisabled : Colors.white;
    }
    
    if (widget.outline) {
      switch (widget.type) {
        case MyButtonType.primary:
          return colors.primary;
        case MyButtonType.success:
          return colors.success;
        case MyButtonType.info:
          return colors.info;
        case MyButtonType.warning:
          return colors.warning;
        case MyButtonType.danger:
          return colors.danger;
        default:
          return colors.text;
      }
    }
    
    switch (widget.type) {
      case MyButtonType.defaultType:
      case MyButtonType.white:
        return colors.text;
      case MyButtonType.link:
        return _isPressed ? colors.primaryDark : (_isHovered ? colors.primaryDark : colors.primary);
      default:
        return Colors.white;
    }
  }

  /// 根据按钮大小获取内边距
  EdgeInsetsGeometry _getPadding(HTheme theme) {
    final dimens = theme.dimens;
    
    switch (widget.size) {
      case MyButtonSize.large:
        return EdgeInsets.symmetric(
          horizontal: dimens.buttonPaddingHorizontalLarge, 
          vertical: dimens.buttonPaddingVerticalLarge
        );
      case MyButtonSize.normal:
        return EdgeInsets.symmetric(
          horizontal: dimens.buttonPaddingHorizontalNormal, 
          vertical: dimens.buttonPaddingVerticalNormal
        );
      case MyButtonSize.small:
        return EdgeInsets.symmetric(
          horizontal: dimens.buttonPaddingHorizontalSmall, 
          vertical: dimens.buttonPaddingVerticalSmall
        );
      case MyButtonSize.mini:
        return EdgeInsets.symmetric(
          horizontal: dimens.buttonPaddingHorizontalMini, 
          vertical: dimens.buttonPaddingVerticalMini
        );
    }
  }

  /// 获取按钮高度
  double _getButtonHeight(HTheme theme) {
    switch (widget.size) {
      case MyButtonSize.large:
        return theme.dimens.buttonHeightLarge;
      case MyButtonSize.normal:
        return theme.dimens.buttonHeightNormal;
      case MyButtonSize.small:
        return theme.dimens.buttonHeightSmall;
      case MyButtonSize.mini:
        return theme.dimens.buttonHeightMini;
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = HTheme.of(context);
    final effects = HEffects(dimens: theme.dimens);
    
    // 构建按钮内容
    Widget buttonChild = Text(
      widget.text,
      style: theme.textStyles.buttonTextWithSize(
        widget.size.toString().split('.').last,
        widget.type.toString().split('.').last,
        outline: widget.outline,
        disabled: widget.disabled,
      ),
    );

    // 如果有图标，则添加图标
    if (widget.icon != null) {
      buttonChild = Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            widget.icon,
            color: _getTextColor(theme),
            size: theme.textStyles
                .buttonTextWithSize(
                  widget.size.toString().split('.').last,
                  widget.type.toString().split('.').last,
                  outline: widget.outline,
                  disabled: widget.disabled,
                )
                .fontSize! * 1.2,
          ),
          SizedBox(width: theme.dimens.spacingM),
          buttonChild,
        ],
      );
    }

    // 构建按钮
    Widget button = MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      cursor: widget.disabled ? SystemMouseCursors.forbidden : SystemMouseCursors.click,
      child: GestureDetector(
        onTapDown: widget.disabled ? null : (_) => setState(() => _isPressed = true),
        onTapUp: widget.disabled ? null : (_) => setState(() => _isPressed = false),
        onTapCancel: widget.disabled ? null : () => setState(() => _isPressed = false),
        onTap: widget.disabled ? null : widget.onPressed,
        child: AnimatedContainer(
          duration: effects.buttonHoverDuration,
          curve: effects.buttonHoverCurve,
          height: _getButtonHeight(theme),
          decoration: BoxDecoration(
            color: _getButtonColor(theme),
            borderRadius: BorderRadius.circular(theme.dimens.borderRadius),
            border: widget.outline
                ? Border.all(
                    color: widget.disabled
                        ? theme.colors.textDisabled
                        : _getTextColor(theme),
                    width: theme.dimens.borderWidth,
                  )
                : null,
            boxShadow: widget.type == MyButtonType.link
                ? null
                : (_isHovered && !widget.disabled
                    ? effects.buttonHoverShadow
                    : null),
          ),
          padding: _getPadding(theme),
          child: Center(child: buttonChild),
        ),
      ),
    );

    // 如果是块级按钮，则调整宽度
    if (widget.block) {
      button = SizedBox(
        width: double.infinity,
        child: button,
      );
    } else {
      // 非块级按钮使用内容宽度
      button = IntrinsicWidth(
        child: button,
      );
    }

    return button;
  }
}

/// 3D按钮组件，实现Miaoyi框架中的3D按钮效果
class HDimButton extends StatefulWidget {
  /// 创建一个Miaoyi风格的3D按钮
  ///
  /// [type] 按钮类型
  /// [icon] 按钮中显示的图标
  /// [size] 按钮大小
  /// [onPressed] 点击回调
  const HDimButton({
    super.key,
    required this.type,
    required this.icon,
    this.size = MyButtonSize.normal,
    this.onPressed,
  });

  /// 按钮类型
  final MyButtonType type;
  
  /// 按钮图标
  final IconData icon;
  
  /// 按钮大小
  final MyButtonSize size;
  
  /// 点击回调
  final VoidCallback? onPressed;

  @override
  State<HDimButton> createState() => _HDimButtonState();
}

class _HDimButtonState extends State<HDimButton> {
  bool _isHovered = false;
  bool _isPressed = false;

  /// 获取图标大小
  double _getIconSize(HTheme theme) {
    switch (widget.size) {
      case MyButtonSize.large:
        return theme.dimens.iconSizeLarge;
      case MyButtonSize.normal:
        return theme.dimens.iconSizeNormal;
      case MyButtonSize.small:
        return theme.dimens.iconSizeSmall;
      case MyButtonSize.mini:
        return theme.dimens.iconSizeSmall * 0.8;
    }
  }

  /// 获取按钮大小
  double _getButtonSize() {
    switch (widget.size) {
      case MyButtonSize.large:
        return 76.0;
      case MyButtonSize.normal:
        return 60.0;
      case MyButtonSize.small:
        return 46.0;
      case MyButtonSize.mini:
        return 36.0;
    }
  }

  /// 获取按钮颜色
  Color _getButtonColor(HTheme theme) {
    final colors = theme.colors;
    
    if (_isPressed) {
      // 按下状态颜色
      switch (widget.type) {
        case MyButtonType.primary:
          return colors.primaryDark;
        case MyButtonType.success:
          return colors.successDark;
        case MyButtonType.info:
          return colors.infoDark;
        case MyButtonType.warning:
          return colors.warningDark;
        case MyButtonType.danger:
          return colors.dangerDark;
        default:
          return const Color(0xFFD9D9D9);
      }
    } else if (_isHovered) {
      // 悬停状态颜色
      switch (widget.type) {
        case MyButtonType.primary:
          return Color.lerp(colors.primary, colors.primaryDark, 0.5)!;
        case MyButtonType.success:
          return Color.lerp(colors.success, colors.successDark, 0.5)!;
        case MyButtonType.info:
          return Color.lerp(colors.info, colors.infoDark, 0.5)!;
        case MyButtonType.warning:
          return Color.lerp(colors.warning, colors.warningDark, 0.5)!;
        case MyButtonType.danger:
          return Color.lerp(colors.danger, colors.dangerDark, 0.5)!;
        default:
          return const Color(0xFFE0E0E0);
      }
    }
    
    // 默认状态颜色
    switch (widget.type) {
      case MyButtonType.primary:
        return colors.primary;
      case MyButtonType.success:
        return colors.success;
      case MyButtonType.info:
        return colors.info;
      case MyButtonType.warning:
        return colors.warning;
      case MyButtonType.danger:
        return colors.danger;
      default:
        return const Color(0xFFE6E6E6);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = HTheme.of(context);
    final effects = HEffects(dimens: theme.dimens);
    final buttonSize = _getButtonSize();
    
    return MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTapDown: (_) => setState(() => _isPressed = true),
        onTapUp: (_) => setState(() => _isPressed = false),
        onTapCancel: () => setState(() => _isPressed = false),
        onTap: widget.onPressed,
        child: SizedBox(
          width: buttonSize,
          height: buttonSize,
          child: AnimatedContainer(
            duration: effects.buttonHoverDuration,
            curve: effects.buttonHoverCurve,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(theme.dimens.borderRadius),
              boxShadow: _isPressed
                  ? []
                  : [
                      BoxShadow(
                        color: _getButtonColor(theme).withOpacity(0.5),
                        blurRadius: 4,
                        spreadRadius: 0,
                        offset: Offset(0, _isHovered ? 6 : 4),
                      ),
                    ],
            ),
            child: Material(
              color: _getButtonColor(theme),
              borderRadius: BorderRadius.circular(theme.dimens.borderRadius),
              child: Center(
                child: AnimatedContainer(
                  duration: effects.buttonPressDuration,
                  curve: effects.buttonPressCurve,
                  transform: _isPressed
                      ? (Matrix4.identity()..translate(0.0, 2.0, 0.0))
                      : Matrix4.identity(),
                  child: Icon(
                    widget.icon,
                    color: Colors.white,
                    size: _getIconSize(theme),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

/// 按钮组组件，实现Miaoyi框架中的按钮组
class MyButtonGroup extends StatelessWidget {
  /// 创建一个按钮组
  ///
  /// [buttons] 按钮列表
  /// [vertical] 是否垂直排列
  const MyButtonGroup({
    super.key,
    required this.buttons,
    this.vertical = false,
  });

  /// 按钮列表
  final List<Widget> buttons;
  
  /// 是否垂直排列
  final bool vertical;

  @override
  Widget build(BuildContext context) {
    final theme = HTheme.of(context);
    
    return ClipRRect(
      borderRadius: BorderRadius.circular(theme.dimens.borderRadius),
      child: vertical
          ? Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: _buildButtonList(theme),
            )
          : Row(
              mainAxisSize: MainAxisSize.min,
              children: _buildButtonList(theme),
            ),
    );
  }

  /// 构建按钮列表
  List<Widget> _buildButtonList(HTheme theme) {
    final List<Widget> buttonList = [];

    for (int i = 0; i < buttons.length; i++) {
      // 添加当前按钮
      buttonList.add(
        _ButtonGroupItem(
          isFirst: i == 0,
          isLast: i == buttons.length - 1,
          isVertical: vertical,
          borderRadius: theme.dimens.borderRadius,
          child: buttons[i],
        ),
      );
    }

    return buttonList;
  }
}

/// 按钮组内部项
class _ButtonGroupItem extends StatelessWidget {
  const _ButtonGroupItem({
    required this.child,
    required this.isFirst,
    required this.isLast,
    required this.isVertical,
    required this.borderRadius,
  });

  final Widget child;
  final bool isFirst;
  final bool isLast;
  final bool isVertical;
  final double borderRadius;

  @override
  Widget build(BuildContext context) {
    BorderRadius borderRadiusValue = BorderRadius.zero;

    if (isVertical) {
      if (isFirst) {
        borderRadiusValue = BorderRadius.only(
          topLeft: Radius.circular(borderRadius),
          topRight: Radius.circular(borderRadius),
        );
      } else if (isLast) {
        borderRadiusValue = BorderRadius.only(
          bottomLeft: Radius.circular(borderRadius),
          bottomRight: Radius.circular(borderRadius),
        );
      }
    } else {
      if (isFirst) {
        borderRadiusValue = BorderRadius.only(
          topLeft: Radius.circular(borderRadius),
          bottomLeft: Radius.circular(borderRadius),
        );
      } else if (isLast) {
        borderRadiusValue = BorderRadius.only(
          topRight: Radius.circular(borderRadius),
          bottomRight: Radius.circular(borderRadius),
        );
      }
    }

    return ClipRRect(
      borderRadius: borderRadiusValue,
      child: child,
    );
  }
}